package com.demo.service.impl;

import java.lang.annotation.Target;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.DataSourceUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.common.annotation.DataSource;
import com.common.datasource.DataSourceKey;
import com.demo.bean.User;
import com.demo.mapper.HelloMapper;
import com.demo.service.HelloService;

@Service

public class HelloServiceImpl implements HelloService {

	@Autowired
	private HelloMapper helloMapper;

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private DataSourceTransactionManager dataSourceTransactionManager;

	/**
	 * 数据库1
	 */
	@Override
	@DataSource(DataSourceKey.DB1)
	public User getUser() {
		return helloMapper.getUser();
	}

	/**
	 * 数据库2
	 */
	@Override
	@DataSource(DataSourceKey.DB2)
	public User getUser2() {
		return helloMapper.getUser();
	}

	/**
	 * 不加DataSource注解(使用默认数据库)
	 */
	@Override
	public User getUserTest() {
		return helloMapper.getUser();
	}

	/**
	 * 加DataSource注解（不指定数据源）使用默认数据库
	 */
	@DataSource
	@Override
	public User getUserTest2() {
		return helloMapper.getUser();
	}

	/**
	 * 加事务
	 */
	@Override
	@DataSource(DataSourceKey.DB1)
	@Transactional
	public void insertTransactional(User user) throws Exception {
		helloMapper.insert(user);
		select();
	}

	/**
	 * 不加事务
	 */
	@Override
	@DataSource(DataSourceKey.DB1)
	public void notTransinsert(User user) throws Exception {
		helloMapper.insert(user);
		select();
	}

	private void select() throws Exception {
		String sql = "select F_ZGBH,F_PASS,F_NAME from bsuser";
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
//			 conn = DataSourceUtils.getConnection(jdbcTemplate.getDataSource());//利用jdbcTemplate拿到DataSource
			conn = DataSourceUtils.getConnection(dataSourceTransactionManager.getDataSource());// 利用事务管理器拿到DataSource
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			User user = new User();
			while (rs.next()) {
				user.setZgbh(rs.getString("F_ZGBH"));
				user.setName(rs.getString("F_NAME"));
				user.setPass(rs.getString("F_PASS"));
			}
			System.out.println("事务未提交前查询结果：" + user.toString());

		} finally {
			// 如果不加事务控制，自己获取的conn需要自己关掉;如果加事务控制,不需要关（都交由spring管理,关了spring在重置conn的时候会异常）
//			if(rs!=null) {
//				rs.close();
//			}
//			if(ps!=null) {
//				ps.close();
//			}
//			if (conn != null) {
//				conn.close();
//			}
		}


	}

}
